package socket2;



import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {

    private Socket socket;
    public Client(){
        try {
            System.out.println("正在连接服务器。。。");
            socket = new Socket("localhost",8080);
            System.out.println("连接成功。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);
            Scanner scanner = new Scanner(System.in);

            System.out.println("请输入昵称");

            while(true){
                String nickname = scanner.nextLine();
                if(nickname.trim().isEmpty()){
                    System.out.println("名字不能为空");
                }else{
                    pw.println(nickname);
                    System.out.println("你好"+nickname+"欢迎加入群聊。");
                    break;
                }
            }
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.setDaemon(true);
            t.start();


            while(true){
                String sendMessage = scanner.nextLine();
                if("exit".equalsIgnoreCase(sendMessage)){
                   break;
                }

                pw.println(sendMessage);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    public class ServerHandler implements Runnable{
        public void run(){
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while((message = br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
